package com.joker.airoleplayplatformback.utils;


import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.joker.airoleplayplatformback.domain.dto.VoiceInfo;
import com.joker.airoleplayplatformback.domain.dto.VoiceResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.util.List;

/**
 * 获取音色列表
 *
 * @author : feixiang.li
 * @since : 2025-09-27 14:02
 */
public class VoiceTypeListUtils {

    private VoiceTypeListUtils() {

    }

    private static final String BASE_URL = "https://openai.qiniu.com/v1";
    private static final ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 简化版本，直接返回音色列表
     */
    public static List<VoiceInfo> getVoices(String apiKey) {
        VoiceResponse response = getVoiceList(apiKey);
        return response.getList();
    }

    /**
     * 获取音色列表
     *
     * @param apiKey API密钥
     * @return VoiceResponse 音色列表响应
     */
    public static VoiceResponse getVoiceList(String apiKey) {
        String url = BASE_URL + "/voice/list";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);

            // 设置请求头
            request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

            // 执行请求
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == 200 && entity != null) {
                String responseString = EntityUtils.toString(entity);
                List<VoiceInfo> voiceInfos = JSON.parseArray(responseString, VoiceInfo.class);
                return new VoiceResponse(voiceInfos);
            } else {
                throw new RuntimeException("请求失败，状态码: " + response.getStatusLine().getStatusCode());
            }

        } catch (IOException e) {
            throw new RuntimeException("获取音色列表失败: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        VoiceResponse voiceList = getVoiceList("sk-05bc0a43150ec29cfe555de2ffcb22a116ff5ee5e7a234c788077d54558e3c85");
        for (VoiceInfo voiceInfo : voiceList.getList()) {
            System.out.println(voiceInfo);
        }
    }

}
